/**
 * Created with JetBrains PhpStorm.
 * User: Ari
 * Date: 8/1/13
 * Time: 8:40 PM
 * To change this template use File | Settings | File Templates.
 */

var EVENT_SOCKET_OPEN = 'socket-open';

var CLIENT_PORT = 7845;
var WEB_SOCKET_URL = 'ws://localhost:' + CLIENT_PORT + '/listen';

var webSocket = new WebSocket(WEB_SOCKET_URL);
var buffer = [];
var open = false;
webSocket.addEventListener('message', function(e) {
    self.postMessage(e.data);
});
webSocket.addEventListener('open', function(e) {
    console.log("WebSocket open", webSocket);
    webSocket.send(EVENT_SOCKET_OPEN);
    open = true;
});
self.addEventListener("message", function (e) {
    if(open) {
        if(buffer.length)
            webSocket.send(buffer.join("\n"));
        webSocket.send(e.data);
        buffer = [];
    } else {
        buffer.push(e.data);
    }
});

